package com.feihao.service.impl;

import com.alibaba.fastjson.JSON;
import com.feihao.domian.Goods;
import com.feihao.domian.QueryParamBean;
import com.feihao.domian.ResultBean;
import com.feihao.mapper.GoodsMapper;
import com.feihao.service.GoodsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RestHighLevelClient client;


    @Override
    public List<Goods> findAll() {
        List<Goods> all = goodsMapper.findAll();
        return all;
    }

    @Override
    public ResultBean pageQuery(QueryParamBean param) {
        System.out.println(param);
        try {
            // 封装查询数据的实体类对象
            ResultBean pageBean = new ResultBean();

            SearchRequest searchRequest = new SearchRequest("goods");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

            Integer page = param.getPage();
            Integer size = param.getSize();

            if (StringUtils.isEmpty(page)) {
                page = 1;
            }
            if (StringUtils.isEmpty(size)) {
                size = 5;
            }
            // 设置分页
            sourceBuilder.size(size);
            int from = (page - 1) * size;
            sourceBuilder.from(from);


            // 如果排序参数不为空，则设置排序规则
            if (!StringUtils.isEmpty(param.getSortOption())&&!StringUtils.isEmpty(param.getSortName())) {
                sourceBuilder.sort(param.getSortName(), SortOrder.fromString(param.getSortOption()));
            }

            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 如果参数中title不为空，则添加对title的分词查询
            if (!StringUtils.isEmpty(param.getTitle())) {
                QueryBuilder matchQuery = QueryBuilders.matchQuery("title", param.getTitle());
                boolQuery.must(matchQuery);
            }

            // 如果参数中higherPrice不为空，则添加对higherPrice的范围查询
            if (!StringUtils.isEmpty(param.getMaxPrice())) {
                RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
                rangeQuery.lte(param.getMaxPrice());
                boolQuery.must(rangeQuery);
            }

            // 如果参数中lowerPrice不为空，则添加对lowerPrice的范围查询
            if (!StringUtils.isEmpty(param.getMinPrice())) {
                RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
                rangeQuery.gte(param.getMinPrice());
                boolQuery.must(rangeQuery);
            }

            sourceBuilder.query(boolQuery);
            searchRequest.source(sourceBuilder);



            // 执行布尔查询
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            // 设置总记录数
            long value = hits.getTotalHits().value;
            pageBean.setTotal((int) value);

            SearchHit[] searchHits = hits.getHits();

            ArrayList<Goods> list = new ArrayList<>();
            for (SearchHit hit : searchHits) {
                String source = hit.getSourceAsString();
                Goods goods = JSON.parseObject(source, Goods.class);
                list.add(goods);
            }
            pageBean.setList(list);
            return pageBean;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
